﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.BZip2;
using System.IO;

namespace OffLineFilter
{
    public enum CompressingType
    {
        Gzip,
        Bz2
    }

    public class FileCompressor
    {
        public String FileName { get; set; }
        private String OutputFileName(CompressingType compressingType)
        {
            String extension = null;
            switch (compressingType)
            {
                case CompressingType.Gzip:
                    extension = ".gz";
                    break;
                case CompressingType.Bz2:
                    extension = ".bz2";
                    break;
                default:
                    break;
            }
            return FileName + extension;
        }

        public FileCompressor(String fileName)
        {
            FileName = fileName;
        }

        public double Compress(CompressingType compressingType)
        {
            FileStream fileToCompressStream = File.Create(OutputFileName(compressingType));
            Stream compressedStream = null;
            switch (compressingType)
            {
                case CompressingType.Gzip:
                    compressedStream = new GZipOutputStream(fileToCompressStream);
                    break;
                case CompressingType.Bz2:
                    compressedStream = new BZip2OutputStream(fileToCompressStream);
                    break;
                default:
                    break;
            }

            using (compressedStream)
            using (FileStream fileStream = File.OpenRead(FileName))
            {
                byte[] buffer = new byte[4096];
                StreamUtils.Copy(fileStream, compressedStream, buffer);
            }

            long sourceSize, compressedSize;
            FileInfo sourceFile = new FileInfo(FileName);
            sourceSize = sourceFile.Length;
            FileInfo compressedFile = new FileInfo(OutputFileName(compressingType));
            compressedSize = compressedFile.Length;

            return (double)compressedSize / (double)sourceSize;
        }
    }
}
